package com.example.cscot;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.Log;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

//
// 这是我常用的函数库
// 都应该是static的，外界可以直接调用的，这里的东西当前APP不一定都用到了，反正平时看到好的功能独立的好函数
// 就都收集起来吧。日积月累，积土成山！
//
// 这里的函数应该是独立明显功能的，不依赖外界全局变量
//
public class LewayHelper {
    public static void initHashMap() {
        // 这个函数不应该在这里，这个是和APP实现紧密相关，并不通用
        String body = readRawFile(WeiLe.mainActivity, "good_prompt");
        String[] lines = body.split("\\n");
        for (String line : lines) {
            if (line.contains("_STR_") || line.contains("_PRP_")) {
                WeiLe.gHashMap.put(line.substring(0, 8), line.substring(9));
            }
        }
        WeiLe.gLogText += TS() + WeiLe.gHashMap.size() + "=gHashMap.size()\n";
    }
    //
    public static String TS() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd日HH:mm:ss.SSS "));
    }

    public static long CTMS() {
        return System.currentTimeMillis();
    }

    public static String logLine(String strLine) {
        return TS() + strLine + "\n";
    }

    public int getScreenWidth() {
        WindowManager manager = (WindowManager) WeiLe.mainActivity.getSystemService(Context.WINDOW_SERVICE);
        return manager.getDefaultDisplay().getWidth();
    }
    public int getScreenHeight() {
        WindowManager manager = (WindowManager) WeiLe.mainActivity.getSystemService(Context.WINDOW_SERVICE);
        return manager.getDefaultDisplay().getHeight();
    }

    // 获取res/raw中的文件列表
    // res/raw需要Context(mainActivity)为媒才能访问到
    // filenName不用考虑路径啦，一般也没必要再res/raw目录下再开目录
    public static String readRawFile(Context context, String fileName) {
        int fileId;
        try {
            Resources resources = context.getResources();
            fileId = resources.getIdentifier(fileName, "raw", context.getPackageName());
            if (fileId <= 0) {
                return "";
            }

            InputStream inputStream = context.getResources().openRawResource(fileId);
            // 使用StringBuilder是为了提高性能
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            inputStream.close();
            return stringBuilder.toString();
        } catch (IOException e) {
            return "";
        }
    }

    // 滚动到低
    public static void scrollToEnd(TextView textView) {
        if (textView.getLayout() != null) {
            int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount()) - textView.getHeight();
            textView.scrollTo(0, Math.max(scrollAmount, 0));
        }
    }

    // 滚动到底
    public static void scrollToEnd(EditText editText) {
        if (editText.getLayout() != null) {
            int scrollAmount = editText.getLayout().getLineTop(editText.getLineCount()) - editText.getHeight();
            editText.scrollTo(0, Math.max(scrollAmount, 0));
        }
    }
    //
    //

    // 所有APP都要处理的动态权限问题
    public static void setMainPermissions(Activity obj) {
        String[] PERMISSIONS_STORAGE = {
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                android.Manifest.permission.INTERNET,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.SYSTEM_ALERT_WINDOW,
                android.Manifest.permission.READ_EXTERNAL_STORAGE};
        for (String s : PERMISSIONS_STORAGE) {
            if (ActivityCompat.checkSelfPermission(obj,
                    s) != PackageManager.PERMISSION_GRANTED) {
                int REQUEST_PERMISSION_CODE = 3;
                ActivityCompat.requestPermissions(obj, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    } // >>> dynamic permission

    public static List<String> getRawFiles(Context context) {
        List<String> list = new ArrayList<>();
        Resources res = context.getResources();     // 获取资源
        Field[] fields = R.raw.class.getFields();   // 获取raw目录下的资源ID
        for (Field field : fields) {
            int resId = 0;
            try {
                resId = field.getInt(field);
            } catch (IllegalAccessException e) {
                Log.d("RawHelper", "IllegalAccessException");
            }
            String fileName = context.getResources().getResourceEntryName(resId);
            list.add(fileName); // 处理具体的文件操作
        }
        return list;
    } // getRawFiles

    public void showToast(final String toast) {
        WeiLe.mainActivity.runOnUiThread(() ->
                Toast.makeText(WeiLe.mainActivity, toast, Toast.LENGTH_SHORT).show());
        return;
    }

    // Android的Internal Storage位于设备内部存储器上，‌具体存储在/data/data/<package name>/files
    // https://blog.csdn.net/gqg_guan/article/details/127903636 很全面
    // FileHelper.copyRawToInternalFile(context, "my_text_file", "my_internal_text_file.txt");
    public static void copyRawToInternalFile(Context context, String rawFile, String internalFile) {
        try {
            InputStream inputStream;
            inputStream = context.getResources().openRawResource(
                    context.getResources().getIdentifier(rawFile, "raw", context.getPackageName()));
            FileOutputStream outputStream = context.openFileOutput(internalFile, Context.MODE_PRIVATE);

            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);

            outputStream.write(buffer);

            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } // copyRawToInternalFile

    // 读取internal storage中的文件，not been tested yet
    public static String readInternalFile(Context context, String internalFile) {
        String fileContent = "";
        try {
            // 打开文件输入流
            FileInputStream fis = context.openFileInput(internalFile);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;

            // 逐行读取
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            // 关闭流
            bufferedReader.close();
            // 文本在sb.toString()中
            fileContent = sb.toString();
        } catch (FileNotFoundException e) {
            // 文件未找到异常处理
            e.printStackTrace();
        } catch (IOException e) {
            // IO异常处理
            e.printStackTrace();
        }
        return fileContent;
    } // readInternalFile
} // >>> LewayHelper
